package com.jeff.android.lab.android.lifecycle.livedata;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.jeff.android.lab.BaseActivity;

public class LiveDataActivity extends BaseActivity {

    private TextView mTvValue;

    private MutableLiveData<String> mLiveData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutView());
        mLiveData = new MutableLiveData<>();

        mLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String value) {
                mTvValue.setText(value);
            }
        });
    }

    private View getLayoutView() {
        final LinearLayout root = new LinearLayout(this);
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        root.setLayoutParams(p);
        root.setOrientation(LinearLayout.VERTICAL);
        root.setFitsSystemWindows(true);

        Button btn = new Button(this);
        btn.setText("设置数据");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLiveData.setValue("Hello World.");
            }
        });
        root.addView(btn);

        mTvValue = new TextView(this);

        mTvValue.setText("你好");
        root.addView(mTvValue);

        return root;
    }

}
